package ar.edu.sovietrussia.customcomponents.librarianstuff;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import services.user.PersonService;
import users.Person;
import ar.edu.sovietrussia.customcomponents.useradmin.UserABMRootComponent;
import ar.edu.sovietrussia.customcomponents.util.InwardReplaceablePanel;
import ar.edu.sovietrussia.customcomponents.util.PersonAndStatusWrapper;

/**
 * Component for Person erasing
 */

@AuthorizeInstantiation("ADMIN")
public class DeleteUserComponent extends InwardReplaceablePanel {

    @SpringBean(name = "service.person")
    private PersonService personService;

    private static final long serialVersionUID = 1L;

    private Form<String> form = new Form<String>("loansByUserForm");

    private List<PersonAndStatusWrapper> personList;

    // --------------------//

    public DeleteUserComponent(final String id, final Class<UserABMRootComponent> clazz) {
        super(id);
        this.setOutputMarkupId(true);

        Form<String> aForm = new Form<String>("deleteUserComponent") {

            private static final long serialVersionUID = 1L;

        };

        aForm.add(new Label("selectUserLabel", "Busqueda de Usuario"));

        ListView listView = this.initializeUsersTable();

        AjaxButton deleteAjaxButton = new AjaxButton("delete_button") {
            private static final long serialVersionUID = 3610707962001534656L;

            @Override
            protected void onSubmit(final AjaxRequestTarget target, final Form<?> aForm) {
                DeleteUserComponent.this.deleteSelectedUsers();

                DeleteUserComponent.this.initializeUsersTable();
                target.add(DeleteUserComponent.this);
            }

            @Override
            protected void onError(final AjaxRequestTarget target, final Form<?> aForm) {
                throw new UnsupportedOperationException();
            }
        };

        aForm.add(listView);

        // Delete Button
        aForm.add(deleteAjaxButton);

        // Delete Button
        aForm.add(new Button("back_button") {
            private static final long serialVersionUID = 3610707852001534656L;

            @Override
            public void onSubmit() {
                DeleteUserComponent.this.goBack(clazz);
            }
        });

        this.add(aForm);

    }

    private ListView initializeUsersTable() {
        this.personList = new ArrayList<PersonAndStatusWrapper>();
        this.personList.addAll(this.wrapUsersForView());

        String personListName = "personList";

        @SuppressWarnings("unchecked")
        ListView listView = new ListView(personListName, this.personList) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void populateItem(final ListItem item) {
                PersonAndStatusWrapper wrapper = (PersonAndStatusWrapper) item.getModelObject();
                item.add(new Label("username", wrapper.getUsername()));
                item.add(new Label("name", wrapper.getName()));
                item.add(new CheckBox("check", new PropertyModel(wrapper, "selected")));
            }
        };
        listView.setReuseItems(false);

        this.replaceIfExists(listView, personListName);

        return listView;
    }

    private void replaceIfExists(final ListView listView, final String componentID) {

        if (this.form.get(componentID) == null) {
            this.form.add(listView);
        } else {
            this.form.replace(listView);
        }
    }

    private List<Person> getSelectedPersonsFromView() {
        Iterator<PersonAndStatusWrapper> it = this.personList.iterator();
        List<Person> ret = new ArrayList<Person>();

        while (it.hasNext()) {
            PersonAndStatusWrapper next = it.next();

            if (next.getSelected()) {
                ret.add(this.personService.getPersonByUsername(next.getUsername()));
            }
        }

        return ret;
    }

    private List<PersonAndStatusWrapper> wrapUsersForView() {
        List<Person> iterable = this.personService.getAllPerson();
        List<PersonAndStatusWrapper> ret = new ArrayList<PersonAndStatusWrapper>();

        for (Person it : iterable) {
            PersonAndStatusWrapper newEntry = new PersonAndStatusWrapper(it.getUserAccount().getUserID(),
                    it.getSurname() + ", " + it.getName());
            ret.add(newEntry);
        }

        return ret;

    }

    private void deleteSelectedUsers() {
        List<Person> selected = this.getSelectedPersonsFromView();

        for (Person it : selected) {
            this.personService.deletePerson(it.getUserAccount().getUserID());
        }

    }

    public Form<String> getForm() {
        return this.form;
    }

    public void setForm(final Form<String> form) {
        this.form = form;
    }
}
